//
//  SCanQRCodeViewController.m
//  
//
//  Created by 张旗 on 8/5/16.
//
//

#import "SCanQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface SCanQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (weak, nonatomic) IBOutlet UIView *scanView;

@property (nonatomic,strong) AVCaptureDevice *m_device;
@property (nonatomic,strong) AVCaptureSession *m_session;
@property (nonatomic,strong) AVCaptureMetadataOutput *metadata_output;
@property (nonatomic,strong) AVCaptureVideoPreviewLayer *m_previewLayer;
@end

@implementation SCanQRCodeViewController

- (void)iniNavigationController
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(dismissNavController) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"Cancel" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn setFrame:CGRectMake(5, 12, 60, 20)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)dismissNavController
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self iniNavigationController];
    [self startPreview];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (AVCaptureSession *)m_session
{
    if (!_m_session) {
        NSError *error;
        _m_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        AVCaptureDeviceInput *input =[AVCaptureDeviceInput deviceInputWithDevice:_m_device error:&error];
        if (!input) {
            NSLog(@"%@",[error localizedDescription]);
        }
        _m_session = [[AVCaptureSession alloc] init];
        if ([_m_session canAddInput:input]) {
            [_m_session addInput:input];
        }
        _metadata_output = [[AVCaptureMetadataOutput alloc] init];
        if ([_m_session canAddOutput:_metadata_output]) {
            [_m_session addOutput:_metadata_output];
        }
        
        dispatch_queue_t videoQueue = dispatch_queue_create("videoQueue", NULL);
        [_metadata_output setMetadataObjectsDelegate:self queue:videoQueue];
        
        // 设置元数据类型
        [_metadata_output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];
        
        _m_previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_m_session];
        [_m_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        [_m_previewLayer setFrame:self.scanView.layer.bounds];
        [self.scanView.layer insertSublayer:_m_previewLayer atIndex:0];
    }
    return _m_session;
}

- (void)startPreview
{
    if (![self.m_session isRunning]) {
        [self.m_session startRunning];
    }
}

- (void)stopPreview
{
    if ([self.m_session isRunning]) {
        [self.m_session stopRunning];
    }
}


#pragma mark -AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects == nil || [metadataObjects count] <= 0) {
        return;
    }
    
    AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
    NSString *result;
    if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
        result = metadataObj.stringValue;
    }
    result = metadataObj.stringValue;
    
    {
        NSLog(@"Your scanning is not QR code..");
    }
    [self performSelectorOnMainThread:@selector(dealwithScanResult:) withObject:result waitUntilDone:NO];
    
}

- (void)dealwithScanResult:(NSString *)result
{
    
    NSLog(@"%@",result);
    
}


@end
